package com.semeureka.fault.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineDecoder;

public class SmsPreparedFilter extends IoFilterAdapter {
	private static final AttributeKey NEXT_PDU = new AttributeKey(SmsPreparedFilter.class, "NEXT_PDU");
	private TextLineDecoder decoder = new TextLineDecoder(LineDelimiter.CRLF);
	private ProtocolDecoderOutput out = new ProtocolDecoderOutput() {
		@Override
		public void write(Object message) {
			// TODO Auto-generated method stub
		}

		@Override
		public void flush(NextFilter nextFilter, IoSession session) {
			// Do nothing
		}
	};

	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		if (message instanceof IoBuffer) {
			IoBuffer buffer = (IoBuffer) message;
			if (buffer.remaining() >= 2 && buffer.getUnsignedShort(buffer.limit() - 2) == 0x3E20) {
				session.write(session.getAttribute(NEXT_PDU));
			} else {
				decoder.decode(session, buffer, out);
			}
		} else {
			nextFilter.messageReceived(session, message);
		}
	}
}
